﻿using Model.DocumentDB;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Studio.DocumentDB
{
    /// <summary>List connected DocDB accounts and their hierarchy.</summary>
    public partial class AccountListControl : UserControl
    {
        /// <summary>Constructor.</summary>
        public AccountListControl()
        {
            InitializeComponent();
        }

        private void TreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            var treeView = sender as TreeView;
            var studio = DataContext as StudioViewModel;

            if (studio != null)
            {   //  Propagates selection
                studio.Accounts.SelectedValue = treeView.SelectedValue;
            }
        }

        private void TreeView_Initialized(object sender, EventArgs e)
        {
            var treeView = sender as TreeView;

            treeView.AddHandler(TreeViewItem.ExpandedEvent, new RoutedEventHandler(TreeItemExpanded));
        }

        private async void TreeItemExpanded(object sender, RoutedEventArgs e)
        {
            var treeViewItem = e.OriginalSource as TreeViewItem;

            if (treeViewItem.IsExpanded)
            {
                var children = treeViewItem.ItemsSource;
                var tasks = from c in children.Cast<object>()
                            let r = c as IRefreshable
                            where r != null
                            select r.EnsureLoadedAsync();

                await ErrorHelper.HandleAsync(
                    () => Task.WhenAll(tasks.ToArray()),
                    this,
                    "Error while reading the databases." + Environment.NewLine + "{0}");
            }
        }
    }
}
